package com.sky.loveshop.utils;

import cn.hutool.json.JSONUtil;
import com.sky.loveshop.entity.WxMiniUser;
import com.sky.loveshop.entity.common.SysConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/11/10 17:11
 */
@Component
public class TokenManager {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成token并存入到redis
     *
     * @param user
     * @return
     */
    public String generateToken(WxMiniUser user) {
        String key = String.format(SysConstants.TOKEN_KEY, user.getId());
        String token = Base64.getEncoder().encodeToString(JSONUtil.toJsonStr(user).getBytes(StandardCharsets.UTF_8));
        redisTemplate.opsForValue().set(key, token, 30, TimeUnit.DAYS);
        return token;
    }

    public Boolean isValidToken(String token) {
        try {
            String userString = new String(Base64.getDecoder().decode(token));
            // 前端传递来的user
            WxMiniUser userFront = JSONUtil.toBean(userString, WxMiniUser.class);
            String key = String.format(SysConstants.TOKEN_KEY, userFront.getId());
            // 后端保存的user
            String value = redisTemplate.opsForValue().get(key);
            String userStringBack = new String(Base64.getDecoder().decode(value));
            WxMiniUser userBack = JSONUtil.toBean(userStringBack, WxMiniUser.class);
            if (StringUtils.isEmpty(value)) {
                return Boolean.FALSE;
            }
            if (!userFront.getOpenId().equals(userBack.getOpenId())) {
                return Boolean.FALSE;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

}
